package com.TCP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.*;

/**
 * @ClassName SocketDemo4
 * @Description TCP多发多收，支持多客户端（线程池）
 * @Author 2214361854
 * @Date 2022/3/3 23:33
 * @Version 1.0
 */
public class SocketDemo4 {
    /**
     * 静态线程池对象
     */
    private static ExecutorService pool = new ThreadPoolExecutor(3,5,6, TimeUnit.SECONDS,new ArrayBlockingQueue<>(2), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
    public static void main(String[] args){
        System.out.println("====服务端启动====");
        try {
            //服务端，创建ServerSocket
            final ServerSocket serverSocket = new ServerSocket(7777);
            //不断接收客户端socket
            while (true) {
                //接收连接请求
                Socket socket = serverSocket.accept();
                System.out.println(socket.getRemoteSocketAddress()+"，上线了！");
                //封装成线程，从线程池处理socket
                pool.execute(new ServerReaderRunnable4(socket));

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        关闭
//        serverSocket.close();
    }
}

/**
 * 客户端
 */
class ClientDemo4{
    public static void main(String[] args) throws Exception {
        System.out.println("====客户端启动====");
        //客户端，创建Soket
        final Socket sk = new Socket("127.0.0.1",7777);
        //获取并包装成字节打印流
        final PrintStream ps = new PrintStream(sk.getOutputStream());
        //发送消息并刷新流
        final Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("TCP客户端：");
            String s = scanner.nextLine();
            ps.println(s);
            ps.flush();
        }
//        关闭
//        sk.close();
    }
}

/**
 * 独立线程
 */
class ServerReaderRunnable4 implements Runnable{
    private Socket socket;

    public ServerReaderRunnable4(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //获取并包装缓冲字符流
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //读取消息
            String msg;
            while ((msg = br.readLine()) != null) {
                System.out.println(socket.getRemoteSocketAddress()+"说了："+msg);
            }
        } catch (Exception e) {
            System.out.println(socket.getRemoteSocketAddress()+"，下线了");
        }
    }
}
